package com.foreveross.chameleon.plugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.foreveross.BroadcastConstant;
import com.foreveross.chameleon.AppStatus;
import com.foreveross.chameleon.CManagerModuleActivity;
import com.foreveross.chameleon.manager.ApplicationSyncListener;
import com.foreveross.chameleon.manager.CubeContentManager;
import com.foreveross.chameleon.manager.R;
import com.foreveross.util.CommonUtil;

/**
 * <BR>
 * [功能详细描述] 策略更新插件
 * 
 */
public class SecurityChangePlugin extends CordovaPlugin {

	private boolean needFinishActivity = true;

	@Override
	public boolean execute(String action, JSONArray args,
			final CallbackContext callbackContext) throws JSONException {
		needFinishActivity = true;
		if (args != null && args.length() > 1) {
			needFinishActivity = args.getBoolean(1);
		}
		if (action.equals("securityChange")) {
			String username = args.getString(0);
			ApplicationSyncListener listener = new ApplicationSyncListener() {

				@Override
				public void syncStart() {
				}

				@Override
				public void syncFail() {
				}

				@Override
				public void syncFinish(String result) {
					callbackContext.success("success");
					// AppStatus.USERLOGIN = true;
					cordova.getActivity().sendBroadcast(
							new Intent(
									BroadcastConstant.SecurityRefreshMainPage));

					if (cordova.getActivity() instanceof CManagerModuleActivity) {
						CManagerModuleActivity activity = (CManagerModuleActivity) cordova
								.getActivity();
						activity.refreshMainPageEvent();
					}
					// 发送广播更新界面
					if (CommonUtil.isPad(cordova.getActivity())) {
						if (cordova.getActivity() instanceof CManagerModuleActivity) {
							cordova.getActivity().runOnUiThread(new Runnable() {
								@Override
								public void run() {
									((CManagerModuleActivity) cordova
											.getActivity())
											.showDetailContent(false);
								}
							});
						}
					} else {
						if (needFinishActivity) {
							cordova.getActivity().finish();
						}
					}

				}
			};
			if (username != null && !username.equals("")) {
				CubeContentManager.getInstance().syncContentPrivilege(true,
						cordova.getActivity(), username, listener, "正在获取账户权限");
			} else {
				callbackContext.error("error user name == null");
			}

		}
		return true;
	}
}